package com.cxs.xiaomi.service.impl;

import com.cxs.xiaomi.dao.UserDao;
import com.cxs.xiaomi.dao.impl.UserDaoImpl;
import com.cxs.xiaomi.domain.User;
import com.cxs.xiaomi.service.UserService;
import com.cxs.xiaomi.utils.*;

import java.util.List;

/*
 * @Author:cxs
 * @Date:2021/9/14  17:54
 * @Version 1.0
 * @Motto:放下杂念,只为迎接明天更好的自己
 * */
public class UserServiceImpl implements UserService {
    private UserDao userDao = new UserDaoImpl();

    @Override
    public boolean checkUsernameExist(String username) {
        return userDao.selectByUsername(username).size() > 0;
    }

    @Override
    public boolean register(User user) {
        if(userDao.selectByUsername(user.getUsername()).size() > 0){
            throw new RuntimeException("用户名已存在");
        }
        if (user.getEmail() != null) {
            String activeCode = StringUtil.generateUniqueKey(20);
            // 密码加密
            user.setPassword(MD5Util.getStringMD5(user.getPassword()));
            user.setCode(activeCode);
            // 发送邮件
            EmailUtils.sendEmail(user);
        }else{
            throw new RuntimeException("邮箱为空");
        }
        // 入库
        return userDao.insert(user) > 0;
    }

    @Override
    public User login(String username, String password) {
        return userDao.selectByUsernameAndPassword(username,password);
    }

    @Override
    public User findById(String userId) {
        return userDao.selectById(Integer.parseInt(userId));
    }

    @Override
    public boolean activeCount(String email, String code) throws Exception {
        // 解码
        String decodeEmail = Base64Utils.decode(email.trim());
        String decodeCode = Base64Utils.decode(code.trim());
        User user = userDao.selectByEmailAndCode(decodeEmail,decodeCode);
        if(user != null){
            // 存在
            if(!user.getFlag().equals(0)){
                throw new Exception("账号已经激活，无需重复操作");
            }
            return userDao.updateCodeById(user.getId(),1) > 0;
        }else{
            throw new Exception("此账号不存在");
        }
    }

    @Override
    public User adminLogin(User user) {
        String username = user.getUsername();
        String password = MD5Util.getStringMD5(user.getPassword());
        if(username != null && password != null){
            User useradmin = userDao.selectByUsernameAndPassword(username, password);
            if(useradmin != null){
                if(useradmin.getRole() != null && useradmin.getRole() == 0){
                    return useradmin;
                }
            }
        }
        return null;
    }

    @Override
    public List<User> userList() {
        return userDao.selectAll();
    }

    @Override
    public boolean del(int id) {
        return userDao.deleteById(id) > 0;
    }

    @Override
    public List<User> likeSearch(String condition, List params) {
        return userDao.selectByUsernameAndGender(condition,params);
    }
}
